package com.fy.utils.aliyunUtils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.BucketStat;
import com.fy.common.config.AppConfig;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Data
@AllArgsConstructor
@Slf4j
@Component
public class AliOssUtil {

    @Autowired
    private AppConfig appConfig;

    //文件上传
    public  String uploadImg(MultipartFile file) throws IOException {
        InputStream inputStream = file.getInputStream();
        String originalFilename = file.getOriginalFilename();
        String fileName = null;
        if (originalFilename != null) {
            fileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
        }
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        String accessKeyId = appConfig.getAccessKeyId();
        String accessKeySecret = appConfig.getAccessKeySecret();
        String bucketName = appConfig.getBucketName();
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        ossClient.putObject(bucketName, fileName, inputStream);
        String url = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/"+fileName;
        ossClient.shutdown();
        return url;
    }


    /**
     * 文件上传
     *
     * @param bytes
     * @param objectName
     * @return
     */
    public String upload(byte[] bytes, String objectName) {
        String endpoint = appConfig.getEndPoint();
        String accessKeyId = appConfig.getAccessKeyId();
        String accessKeySecret = appConfig.getAccessKeySecret();
        String bucketName = appConfig.getBucketName();

        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            if (ossClient.doesObjectExist(bucketName, objectName)) {
                ossClient.deleteObject(bucketName, objectName);
                log.info("Deleted existing file: {}", objectName);
            }

            ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(bytes));
        } catch (OSSException | ClientException e) {
            log.error("Error occurred while uploading file", e);
            throw new RuntimeException(e);
        } finally {
            if (ossClient!= null) {
                ossClient.shutdown();
            }
        }

        StringBuilder stringBuilder = new StringBuilder("https://")
                .append(bucketName)
                .append(".")
                .append(endpoint)
                .append("/")
                .append(objectName);

        log.info("文件上传到:{}", stringBuilder.toString());

        return stringBuilder.toString();
    }

    /**
     * 删除云存储数据
     *
     * @param objectName
     */
    public void delete(String objectName) {
        String endpoint = appConfig.getEndPoint();
        String accessKeyId = appConfig.getAccessKeyId();
        String accessKeySecret = appConfig.getAccessKeySecret();
        String bucketName = appConfig.getBucketName();

        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            ossClient.deleteObject(bucketName, objectName);
            log.info("Deleted file: {}", objectName);
        } catch (OSSException | ClientException e) {
            log.error("Error occurred while deleting file", e);
            throw new RuntimeException(e);
        } finally {
            if (ossClient!= null) {
                ossClient.shutdown();
            }
        }
    }

    /**
     * 获取OSS空间使用信息
     *
     * @return
     */
    public BucketStat getBucketStat() {
        String endpoint = appConfig.getEndPoint();
        String accessKeyId = appConfig.getAccessKeyId();
        String accessKeySecret = appConfig.getAccessKeySecret();
        String bucketName = appConfig.getBucketName();

        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            return ossClient.getBucketStat(bucketName);
        } catch (OSSException | ClientException e) {
            log.error("Error occurred while getting bucket stat", e);
            throw new RuntimeException(e);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}